package com.heye.imheye.security;

import com.heye.imheye.dto.UserInfo;
import com.heye.imheye.repository.UserRepository;
import jakarta.servlet.http.HttpSession;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@RequiredArgsConstructor
public class SecurityConfig {

    private final UserRepository userRepository;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

    @Bean
    public UserDetailsService userDetailsService() {
        return new MyUserDetailsService(userRepository);
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.csrf(AbstractHttpConfigurer::disable);
        http.formLogin(formLogin -> {
            formLogin.successHandler((request, response, authentication) -> {
                if (authentication instanceof UsernamePasswordAuthenticationToken token) {
                    MyUserDetails userDetails = (MyUserDetails) token.getPrincipal();
                    UserInfo userInfo = new UserInfo(userDetails.getUser().getId());
                    HttpSession session = request.getSession();
                    session.setAttribute("user", userInfo);
                }
            });
        });
        http.authorizeHttpRequests(auth -> {
            auth.requestMatchers("/css/**", "/js/**", "/test/test0", "/register/**", "/ws").permitAll()
                    .anyRequest().hasRole("USER");
        });

        DefaultSecurityFilterChain build = http.build();
        return build;
    }
}
